package com.lovo.controller;

import com.lovo.result.GlobalHandleException;
import com.lovo.result.ResponseResult;
import com.lovo.result.ResultCode;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.Date;

/**
 * @title
 * @author: luo
 * @date: 2020/11/23 20:40
 */
@RestController
@ResponseResult
@RequestMapping("/api/session")
public class SessionController {

    @ResponseResult
    @GetMapping("/getSession")
    @ResponseBody
    public Object getSession(HttpServletRequest request) throws GlobalHandleException {
        Object user = request.getSession().getAttribute("user");
        if(user == null){
            throw new GlobalHandleException(ResultCode.USER_NOT_LOGGED_IN);
        }
        return user;
    }

    @ResponseResult
    @GetMapping("/removeSession")
    @ResponseBody
    public Object removeSession(HttpServletRequest request){
        request.getSession().removeAttribute("user");
        return null;
    }

    @PostMapping("/upload")
    @ResponseBody
    public String upload(@RequestParam(value = "file", required = false) MultipartFile file, HttpServletRequest request, Model model) {
//        String path = request.getSession().getServletContext().getRealPath("static/upload");
        String path = "d:/server/upload";
        // 获取上传图片的文件名
        String fileName = file.getOriginalFilename();
        // 截取后缀名
        String suffixName = fileName.substring(fileName.lastIndexOf("."));
        // 生成新的文件名（时间 + 随机数 + 后缀名）
        String newFileName = new Date().getTime() + "_" + String.valueOf(Math.random()).substring(2) + suffixName;
        File targetFile = new File(path, newFileName);
        if (!targetFile.exists()) {
            targetFile.mkdirs();
        }
        // 保存
        try {
            file.transferTo(targetFile);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return newFileName;
    }


}
